<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useMessage } from 'naive-ui'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'

interface Note {
  id: string
  title: string
  content: string
  createdAt: number
  updatedAt: number
}

const message = useMessage()
const notes = ref<Note[]>([])
const showEditor = ref(false)
const currentNote = ref<Note | null>(null)
const searchText = ref('')

// 编辑器状态
const editTitle = ref('')
const editContent = ref('')
const isEditing = ref(false)

// 从 localStorage 加载笔记
const loadNotes = () => {
  const savedNotes = localStorage.getItem('notes')
  if (savedNotes) {
    notes.value = JSON.parse(savedNotes)
  }
}

// 保存笔记到 localStorage
const saveNotes = () => {
  localStorage.setItem('notes', JSON.stringify(notes.value))
}

// 创建新笔记
const createNote = () => {
  showEditor.value = true
  isEditing.value = false
  currentNote.value = null
  editTitle.value = ''
  editContent.value = ''
}

// 保存笔记
const saveNote = () => {
  if (!editTitle.value.trim()) {
    message.warning('请输入标题')
    return
  }

  if (isEditing.value && currentNote.value) {
    // 更新现有笔记
    const index = notes.value.findIndex(n => n.id === currentNote.value!.id)
    if (index !== -1) {
      notes.value[index] = {
        ...currentNote.value,
        title: editTitle.value,
        content: editContent.value,
        updatedAt: Date.now()
      }
      message.success('笔记已更新')
    }
  } else {
    // 创建新笔记
    const newNote: Note = {
      id: Date.now().toString(),
      title: editTitle.value,
      content: editContent.value,
      createdAt: Date.now(),
      updatedAt: Date.now()
    }
    notes.value.unshift(newNote)
    message.success('笔记已创建')
  }

  saveNotes()
  showEditor.value = false
}

// 编辑笔记
const editNote = (note: Note) => {
  currentNote.value = note
  editTitle.value = note.title
  editContent.value = note.content
  isEditing.value = true
  showEditor.value = true
}

// 删除笔记
const deleteNote = (note: Note) => {
  if (confirm('确定要删除这条笔记吗？')) {
    notes.value = notes.value.filter(n => n.id !== note.id)
    saveNotes()
    message.success('笔记已删除')
    if (currentNote.value?.id === note.id) {
      showEditor.value = false
    }
  }
}

// 复制笔记内容
const copyNote = async (note: Note) => {
  try {
    await navigator.clipboard.writeText(note.content)
    message.success('笔记内容已复制')
  } catch (err) {
    message.error('复制失败，请手动复制')
  }
}

// 格式化时间
const formatTime = (timestamp: number) => {
  return format(timestamp, 'yyyy年MM月dd日 HH:mm:ss', { locale: zhCN })
}

// 过滤笔记
const filteredNotes = computed(() => {
  if (!searchText.value) return notes.value
  const search = searchText.value.toLowerCase()
  return notes.value.filter(note =>
    note.title.toLowerCase().includes(search) ||
    note.content.toLowerCase().includes(search)
  )
})

// 取消编辑
const cancelEdit = () => {
  showEditor.value = false
}

onMounted(() => {
  loadNotes()
})
</script>

<template>
  <div class="p-4 mx-auto max-w-7xl">
    <n-card>
      <template #header>
        <div class="text-2xl font-bold">记事本</div>
        <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">
          本地笔记本，支持创建、编辑、删除和搜索笔记
        </p>
      </template>

      <n-space vertical>
        <!-- 工具栏 -->
        <div class="flex items-center justify-between gap-4">
          <n-input
            v-model:value="searchText"
            type="text"
            placeholder="搜索笔记..."
            class="max-w-xs"
          />
          <n-button type="primary" @click="createNote">
            新建笔记
          </n-button>
        </div>

        <!-- 笔记列表和编辑器 -->
        <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
          <!-- 笔记列表 -->
          <div class="space-y-4">
            <template v-if="filteredNotes.length">
              <n-card
                v-for="note in filteredNotes"
                :key="note.id"
                :bordered="false"
                class="transition-shadow cursor-pointer bg-gray-50 dark:bg-gray-800 hover:shadow-md"
                @click="editNote(note)"
              >
                <div class="flex items-start justify-between">
                  <div class="flex-1 space-y-2">
                    <h3 class="font-medium">{{ note.title }}</h3>
                    <p class="text-sm text-gray-600 dark:text-gray-400 line-clamp-2">
                      {{ note.content }}
                    </p>
                    <div class="text-xs text-gray-500">
                      创建于: {{ formatTime(note.createdAt) }}
                      <br>
                      更新于: {{ formatTime(note.updatedAt) }}
                    </div>
                  </div>
                  <div class="flex gap-2 ml-4">
                    <n-button
                      tertiary
                      size="small"
                      @click.stop="copyNote(note)"
                    >
                      复制
                    </n-button>
                    <n-button
                      tertiary
                      type="error"
                      size="small"
                      @click.stop="deleteNote(note)"
                    >
                      删除
                    </n-button>
                  </div>
                </div>
              </n-card>
            </template>
            <div v-else class="py-8 text-center text-gray-500">
              暂无笔记
            </div>
          </div>

          <!-- 编辑器 -->
          <div v-if="showEditor" class="space-y-4">
            <n-input
              v-model:value="editTitle"
              type="text"
              placeholder="笔记标题"
            />
            <n-input
              v-model:value="editContent"
              type="textarea"
              placeholder="笔记内容..."
              :autosize="{ minRows: 10, maxRows: 20 }"
            />
            <div class="flex justify-end gap-2">
              <n-button @click="cancelEdit">
                取消
              </n-button>
              <n-button type="primary" @click="saveNote">
                保存
              </n-button>
            </div>
          </div>
        </div>
      </n-space>
    </n-card>
  </div>
</template>

<style scoped>
:deep(.n-input) {
  font-family: monospace;
}
</style> 